package Java基础.线程池;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Title
 * @Author zhengqiang.tan
 * @Date 2021/3/28 4:20 PM
 */
public class T03_CachePool {
    public static void main(String[] args) throws InterruptedException {

        /**
         * 使用的是 SynchronousQueue 来一个任务必须得到处理，不会缓存task,不推荐
         */
        ExecutorService service =  Executors.newCachedThreadPool();
//        ExecutorService service1 = Executors.newSingleThreadExecutor();
//        ExecutorService service2 = Executors.newFixedThreadPool(4);
//        ExecutorService service3 = Executors.newScheduledThreadPool(4);
//        ExecutorService service4 = Executors.newSingleThreadScheduledExecutor();



        System.out.println(service);


        for (int i = 0; i < 2; i++) {
            service.execute(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
            });
        }

        System.out.println(service);

        TimeUnit.SECONDS.sleep(65); // 超时自动回收

        System.out.println(service);


    }
}
//        java.util.concurrent.ThreadPoolExecutor@3b9a45b3[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
//        java.util.concurrent.ThreadPoolExecutor@3b9a45b3[Running, pool size = 2, active threads = 2, queued tasks = 0, completed tasks = 0]
//        pool-1-thread-1
//        pool-1-thread-2
//        java.util.concurrent.ThreadPoolExecutor@3b9a45b3[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 2]